package iyuwu.EasyTrade;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

public class EventListener implements Listener {
    public File Folder= new File(System.getProperty("user.dir")+"/plugins/EasyTrade/TradeList");
    public File Fold= new File(System.getProperty("user.dir")+"/plugins/EasyTrade/Left");
    public File temp= new File(System.getProperty("user.dir")+"/plugins/EasyTrade/temp");
    final int[] UnMoveAble={0,1,2,3,4,5,6,7,8,9,17,18,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,19,20,21,22,23,24,25,45,53};
    final int[] UnMoveAbleInfo={10,11,12,13,14,15,16,28,29,30,31,32,33,34};
    public boolean contains(int[] a,int b){
        for(int i : a){
            if(i==b)return true;//数组a里是否含有b
        }
        return false;
    }
    @EventHandler
    public void onInventoryMoveItemEvent(InventoryMoveItemEvent e){
        ItemStack item=e.getItem();
        ItemMeta im = item.hasItemMeta()?item.getItemMeta():Bukkit.getItemFactory().getItemMeta(item.getType());
        if(!im.hasLore())return;
        if(im.getLore().contains("不可移动")){
            e.setCancelled(true);
            return;
        }
    }
    @EventHandler
    public void onInventoryClick(InventoryClickEvent e){
        if(e.getWhoClicked().getOpenInventory().getTitle().contains("Create")&&contains(UnMoveAble,e.getRawSlot())) {
            e.setCancelled(true);
            if(e.getRawSlot()>=28&&e.getRawSlot()<=34){//into more items gui
                Inventory infoInv=Bukkit.createInventory(null,54,"Choose");
                 new SetGUI().ChooseGUI(infoInv,1);
                e.getWhoClicked().closeInventory();
                e.getWhoClicked().openInventory(infoInv);
            }

            if(e.getRawSlot()==22){
                ArrayList<ItemStack> sale = new ArrayList<>();
                for(int i=10;i<=16;i++){
                    if(e.getWhoClicked().getOpenInventory().getItem(i)!=null)
                        sale.add(e.getWhoClicked().getOpenInventory().getItem(i));
                }
                ArrayList<ItemStack> want = new ArrayList<>();
                for(int i=28;i<=34;i++){
                    if(e.getWhoClicked().getOpenInventory().getItem(i)!=null)
                        want.add(e.getWhoClicked().getOpenInventory().getItem(i));
                        e.getWhoClicked().getInventory().addItem(e.getWhoClicked().getOpenInventory().getItem(i));
                }
                YamlConfiguration yml = YamlConfiguration.loadConfiguration(new File(this.Folder+"/"+e.getWhoClicked().getOpenInventory().getTitle().substring(7)+".yml"));
                yml.set("sale",null);
                yml.set("Owner",e.getWhoClicked().getOpenInventory().getPlayer().getName());
                for(int index=0;index<sale.size();index++){
                    if(sale.get(index).getType()!= Material.AIR && sale.get(index) !=null){
                        yml.set("sale."+index, sale.get(index));
                    }
                }
                yml.set("want",null);
                for(int index=0;index<want.size();index++){
                    if(want.get(index).getType()!= Material.AIR && want.get(index) !=null){
                        yml.set("want."+index, want.get(index));
                    }
                }
                try {
                    yml.save(this.Folder+"/"+e.getWhoClicked().getOpenInventory().getTitle().substring(7)+".yml");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                Collection<? extends Player> p=Bukkit.getOnlinePlayers();
                for(Player i:p){
                    i.sendMessage("玩家 "+e.getWhoClicked().getName()+" 创建了交易 "+e.getWhoClicked().getOpenInventory().getTitle().substring(7));
                }
                e.getWhoClicked().closeInventory();
                e.getWhoClicked().sendMessage("交易保存成功");
            }
        }
        if(e.getWhoClicked().getOpenInventory().getTitle().contains("Info") &&(contains(UnMoveAble,e.getRawSlot()) || contains(UnMoveAbleInfo,e.getRawSlot()))){
            e.setCancelled(true);
            if(e.getRawSlot()==22){
                boolean IsOk=true;
                for(int i=1;i<=7;i++){
                    if(e.getWhoClicked().getOpenInventory().getItem(i+27).getType() != e.getWhoClicked().getOpenInventory().getItem(i+45).getType() ||e.getWhoClicked().getOpenInventory().getItem(i+27).getAmount() != e.getWhoClicked().getOpenInventory().getItem(i+45).getAmount()){
                        e.getWhoClicked().sendMessage("放置的物品与所需要的不同");//判断是否一致
                        IsOk=false;
                        break;
                    }
                }
                if(IsOk){
                    for(int i=1;i<=7;i++){
                        e.getWhoClicked().getInventory().addItem(new ItemStack(e.getWhoClicked().getOpenInventory().getItem(i+9).getType(),e.getWhoClicked().getOpenInventory().getItem(i+9).getAmount()));
                    }
                    File f=new File(this.Folder+"/"+e.getWhoClicked().getOpenInventory().getTitle().substring(5)+".yml");
                    YamlConfiguration yml = YamlConfiguration.loadConfiguration(f);
                    String Owner=yml.getString("Owner");
                    e.getWhoClicked().sendMessage("你与 "+Owner+" 成功交易");
                    Collection<? extends Player> p=Bukkit.getOnlinePlayers();
                    Player tmp=null;
                    boolean IsFound=false;
                    for(Player i:p){
                        if(i.getName().equals(Owner)){
                            for(int j=1;j<=7;j++){
                                i.getInventory().addItem(new ItemStack(e.getWhoClicked().getOpenInventory().getItem(j+27).getType(),e.getWhoClicked().getOpenInventory().getItem(j+27).getAmount()));
                            }
                            tmp=i;
                            IsFound=true;
                            break;
                        }
                    }
                    if(IsFound){
                        tmp.sendMessage("你的交易 "+e.getWhoClicked().getOpenInventory().getTitle().substring(5)+" 已与玩家 "+e.getWhoClicked().getName()+" 完成");
                        f.delete();
                    }
                    else{
                        File fl=new File(Fold+"/"+Owner+".yml");
                        yml.set("IsDone",true);
                        try {
                            yml.save(f);
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                        YamlConfiguration left=YamlConfiguration.loadConfiguration(new File(this.Fold +"/"+ Owner+".yml"));
                        int tot;
                        if(left.get("Total")==null)tot=0;
                        else tot=left.getInt("Total");
                        tot++;left.set("Total",tot);
                        left.set(String.valueOf(tot),e.getWhoClicked().getOpenInventory().getTitle().substring(5));
                        try {
                            left.save(fl);
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                    for(int index=0;index<=53;index++)
                        e.getWhoClicked().getOpenInventory().setItem(index,null);
                    e.getWhoClicked().closeInventory();
                }
            }
        }
        if(e.getWhoClicked().getOpenInventory().getTitle().equals("Choose")){
            e.setCancelled(true);
            ItemStack pageItem=e.getInventory().getItem(47);
            int page=pageItem.getItemMeta().getDisplayName().toCharArray()[2]-'0';
            if(pageItem.getItemMeta().getDisplayName().toCharArray().length==4){
                page=page*10+pageItem.getItemMeta().getDisplayName().toCharArray()[3]-'0';
            }
            if(e.getRawSlot()==45&&page!=1){

                System.out.println(page);
                Inventory inv=Bukkit.createInventory(null,54,"Choose");
                new SetGUI().ChooseGUI(inv,page-1);
                e.getWhoClicked().openInventory(inv);
            }
            if(e.getRawSlot()==53&&page!=13){
                System.out.println(page);
                Inventory inv=Bukkit.createInventory(null,54,"Choose");
                new SetGUI().ChooseGUI(inv,page+1);
                e.getWhoClicked().openInventory(inv);
            }
        }
        //玩家点击GUI之外不是格子的地方也会触发InventoryClickEvent, 处理
        if(e.getRawSlot()<0 || e.getRawSlot()>e.getInventory().getSize() || e.getInventory()==null)
            return;
    }
    @EventHandler
    public void onInventoryClose(InventoryCloseEvent e){
        if(e.getInventory().getTitle().contains("Create")){
            String name=e.getInventory().getTitle().substring(7);
            File Had=new File(Folder+"/"+name+".yml");
            File TmpFile=new File(temp+"/"+name+".yml");
            if(!TmpFile.exists()){
                if(Had.exists())return;
                else{
                    YamlConfiguration yml=YamlConfiguration.loadConfiguration(TmpFile);
                    for(int index=0;index<45;index++){
                        if(e.getInventory().getItem(index).getType()!=Material.AIR)
                            yml.set(String.valueOf(index),e.getInventory().getItem(index));
                    }
                    try {
                        yml.save(TmpFile);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
        }
        if(e.getInventory().getTitle().contains("Info")){
            for(int index=46;index<53;index++){
                if(e.getInventory().getItem(index).getType()!=Material.AIR){
                    e.getPlayer().getInventory().addItem(e.getInventory().getItem(index));
                }
            }
        }
    }
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent e){
        e.getPlayer().sendMessage(ChatColor.RED+"[EasyTrade]EasyTrade正在施工，除了开发者，用的找打");
        String s=e.getPlayer().getName();
        File fl=new File(Fold+"/"+s+".yml");
        if(!fl.exists()){
            return;
        }
        else{
            YamlConfiguration yml=YamlConfiguration.loadConfiguration(fl);
            int tot=yml.getInt("Total");
            for(int index=1;index<=tot;index++){
                String i=yml.getString(String.valueOf(index));
                File k=new File(Folder+"/"+i+".yml");
                if(!k.exists()){
                    continue;
                }
                else{
                    YamlConfiguration tmpyml=YamlConfiguration.loadConfiguration(k);
                    ConfigurationSection ymlop=tmpyml.getConfigurationSection("want");
                    for(String s1:ymlop.getKeys(false)){
                        ItemStack tmpItem=ymlop.getItemStack(s1);
                        e.getPlayer().getInventory().addItem(tmpItem);
                    }
                }
                e.getPlayer().sendMessage("你的交易 "+i+" 已结算");
                k.delete();
            }
        }
    }
}